package org.iblink.core.domain.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.iblink.core.domain.dao.CategoryDao;
import org.iblink.core.domain.model.Category;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * Category DAO access implementation.
 * 
 * @author tpares
 *
 */
public class CategoryDaoImpl extends HibernateDaoSupport implements CategoryDao {

  private static final Logger logger = Logger.getLogger(CategoryDaoImpl.class.getName());
  
  @Override
  /**
   * {@inheritDoc}
   */
  public void deleteCategory(final long id) {
    logger.debug("Delete category " + id);
    final Category category = getHibernateTemplate().load(Category.class, id);
    getHibernateTemplate().delete(category);
  }

  @SuppressWarnings("unchecked")
  @Override
  /**
   * {@inheritDoc}
   */
  public List<Category> getCategories() {
    logger.debug("Get all categories");
    return (List<Category>) getHibernateTemplate().find("from Category");
  }

  @Override
  /**
   * {@inheritDoc}
   */
  public Category getCategory(final long id) {
    logger.debug("Load category " + id);
    return getHibernateTemplate().get(Category.class, id);
  }

  @Override
  /**
   * {@inheritDoc}
   */
  public void saveCategory(final Category category) {
    logger.debug("Save/Update category " + category.getId());
    getHibernateTemplate().saveOrUpdate(category);
  }
  
  @SuppressWarnings("unchecked")
  @Override
  /**
   * {@inheritDoc}
   */
  public List<Category> getSubCategories(final long id) {
    logger.debug("Get sub categories");
    
    final StringBuffer query = new StringBuffer();
    query.append("select category from category in ").append(Category.class);
    query.append(" where category.parent.id = :categoryId order by category.name");
    
    return getHibernateTemplate().findByNamedParam(query.toString(), "categoryId", id);
  }
  
  /**
   * {@inheritDoc}
   */
  @SuppressWarnings("unchecked")
  public List<Category> getRoots() {
    logger.debug("Get root category");
    
    final StringBuffer query = new StringBuffer();
    query.append("select category from category in ").append(Category.class);
    query.append(" where category.parent is null");
    
    return getHibernateTemplate().find(query.toString());
  }
}
